//
//  YJQSpeaker.m
//  GoodLuck
//
//  Created by 杨瑞 on 17/2/20.
//  Copyright © 2017年 杨瑞. All rights reserved.
//

#import "YJQSpeaker.h"
#import <AVFoundation/AVFoundation.h>
#import <NSString+HMNumberConvert.h>

@implementation YJQSpeaker {
    NSString * _typeStr;
    AVPlayer * _player;
    /// 上次播报距离
    double _lastReportDistance;
    /// 声音字典
    NSDictionary *_voiceDictionary;
    
    NSMutableArray *_voiceArray;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _unitDistance = 1;
        _lastReportDistance = 0;
        //json反序列化
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"voice.json" withExtension:nil subdirectory:@"voice.bundle"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        _voiceDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        _player = [AVPlayer new];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playItemDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        // 4. 允许多个应用程序的音乐同时播放！- 一旦应用程序退出到后台，应该同样能够播放音乐！
        // 音乐会话分类 - 专门解决多个音乐播放设置的，而且代码相对固定！
        // 因为在 iOS 中，默认的音乐播放是`独占`的！
        // AVAudioSessionCategoryOptionMixWithOthers - 允许和其他的音乐一起播放，但是音量相同
        // AVAudioSessionCategoryOptionDuckOthers - 允许和其他音乐一起播放，会降低其他音乐的音量，但是，无法恢复音量
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:NULL];
        // - 在开始播放语音之前，激活音乐会话，表示之前设置的分类有效
        // - 在所有的语音播放结束之后，禁用音乐会话，表示之前设置的分类暂时无效
        [[AVAudioSession sharedInstance] setActive:YES error:NULL];
    }
    return self;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)startSportWithType:(YJQSportType)type {
    switch (type) {
        case YJQSportTypeWalk:
            _typeStr = @"走路";
            break;
        case YJQSportTypeRun:
            _typeStr = @"跑步";
            break;
        case YJQSportTypeRide:
            _typeStr = @"骑行";
            break;
    }
    _typeStr = [@"开始" stringByAppendingString:_typeStr];
    [self playVoiceWithText:_typeStr];
}

-(void)sportStateChangeWithState:(YJQSportState)state {
    NSString *text;
    switch (state) {
        case YJQSportStateContinue:
            text = @"运动已恢复";
            break;
        case YJQSportStatePause:
            text = @"运动已暂停";
            break;
        case YJQSportStateFinish:
            text = @"放松一下吧";
            break;
    }
    [self playVoiceWithText:text];
}

-(void)reportWithDistance:(double)distance time:(NSTimeInterval)time speed:(double)speed {
    // 判断总距离和单位距离+末次报告距离之间的关系
    if (distance < _unitDistance + _lastReportDistance) {
        return;
    }
    // 记录上次播报距离
    _lastReportDistance = (NSInteger)(distance / _unitDistance) * _unitDistance;
    NSString *distanceStr = [NSString hm_numberStringWithNumber:distance hasDotNumber:YES];
    NSString *timeStr = [NSString hm_timeStringWithTimeValue:time];
    NSString *speedStr = [NSString hm_numberStringWithNumber:speed hasDotNumber:YES];
    NSString *fmt = @"你已经 %@ %@ 公里 用时 %@ 平均速度 %@ 公里每小时 太棒了";
    NSString *text = [NSString stringWithFormat:fmt, _typeStr, distanceStr, timeStr, speedStr];
    [self playVoiceWithText:text];
}
/**
 语音播报方法

 @param text 播报内容
 */
- (void)playVoiceWithText:(NSString *)text {
    NSLog(@"播放语音内容 - %@", text);
    NSArray *array = [text componentsSeparatedByString:@" "];
    _voiceArray = [NSMutableArray arrayWithArray:array];
//    NSString *key = array.firstObject;
//    NSString *mp3 = _voiceDictionary[key];
//    NSURL *url = [[NSBundle mainBundle] URLForResource:mp3 withExtension:nil subdirectory:@"voice.bundle"];
//    if (url == nil) {
//        NSLog(@"%@ 对应的 mp3 没有找到", text);
//        return;
//    }
//    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
//    [_player replaceCurrentItemWithPlayerItem:item];
//    [_player play];
    // 3. 激活音乐会话 - 之前设置的分类有效
    [[AVAudioSession sharedInstance] setActive:YES error:NULL];
    [self playFirstVoice];
}

- (void)playFirstVoice {
    if (_voiceArray.count == 0) {
        // 禁用音乐会话 - 恢复其他音乐的音量
        [[AVAudioSession sharedInstance] setActive:NO error:NULL];
        return;
    }
    NSString *key = _voiceArray.firstObject;
    [_voiceArray removeObjectAtIndex:0];
    NSString *mp3 = _voiceDictionary[key];
    NSURL *url = [[NSBundle mainBundle] URLForResource:mp3 withExtension:nil subdirectory:@"voice.bundle"];
    if (url == nil) {
        [self playFirstVoice];
        NSLog(@"%@ 对应的 mp3 没有找到", key);
        return;
    }
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    [_player replaceCurrentItemWithPlayerItem:item];
    [_player play];

}


- (void)playItemDidEnd:(NSNotification *)notification {
    NSLog(@"bobaowanbi");
    [self playFirstVoice];
}

@end
